
#import "PywFloatView.h"
#import "UIImage+Pyw.h"
#import "PywPlatformMain.h"
#import "PywSdk+center.h"

//点击后扩大的大小
#define SCALESIZE 5

//展开菜单view的标记
#define MENUBGTAG 1

typedef NS_ENUM (NSUInteger, LocationTag) {
    kLocationTag_top = 1,
    kLocationTag_left,
    kLocationTag_bottom,
    kLocationTag_right
};

@interface PywFloatView ()
{
    UIImageView *_bannerIV;//浮标的imageview
    
    BOOL _bMoving;//是否在移动浮标
    BOOL _hiding; //是否在隐藏
    BOOL _scheduling; //是否正在消息调度
    float _nLogoWidth;//浮标的宽度
    float _nLogoHeight;//浮标的高度
    float _nMenuWidth;//菜单栏的宽度
    float _nMenuHeight;//菜单栏的高度＝＝浮标的宽度
    
    LocationTag _locationTag;
    float _w;
    float _h;
    UIInterfaceOrientation _orientation;
    NSTimer *_timer;
}

// 竖屏情况下self.view的height
@property (nonatomic, assign)CGFloat v_height;
// 竖屏情况下self.view的width
@property (nonatomic, assign)CGFloat v_width;
// 横屏情况下self.view的height
@property (nonatomic, assign)CGFloat h_height;
// 横屏情况下self.view的width
@property (nonatomic, assign)CGFloat h_width;

@end

static PywFloatView *_instance;

@implementation PywFloatView

+ (PywFloatView *)shareObject
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        CGRect frame = CGRectMake(0, 60, IS_IPAD ? 75:50, IS_IPAD?75:50);
        
        NSString *location = [[NSUserDefaults standardUserDefaults] objectForKey:@"float_location"];

        if (location.length >0 && location != nil) {
            frame = CGRectFromString(location);
        }
        _instance = [[PywFloatView alloc] initWithFrame:frame menuWidth:IS_IPAD?300:150];
        [_instance setBannerImageView:YES];
    });
    
    return _instance;
}


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        [self initV:frame menuWidth:200];
    }
    return self;
}


- (id)initWithFrame:(CGRect)frame menuWidth:(float)nWidth
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self initV:frame menuWidth:nWidth];
    }
    return self;
}

- (void)initV:(CGRect)frame menuWidth:(float)nWidth
{
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rememberLocation) name:UIApplicationDidEnterBackgroundNotification object:nil];
    _bMoving = NO;
    _hiding = NO;
    _locationTag = kLocationTag_bottom;
    
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    
    if (orientation == UIInterfaceOrientationLandscapeLeft || orientation ==
        UIInterfaceOrientationLandscapeRight) {
        _w = self.h_width;
        _h = self.h_height;
    }else{
        _w = self.v_width;
        _h = self.v_height;
    }
    
    _orientation = orientation;
    
    _locationTag = kLocationTag_bottom;
    _nLogoWidth = frame.size.width;
    _nLogoHeight = frame.size.height;
    
    
    _bannerIV = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, _nLogoWidth - 10, _nLogoHeight - 10)];
    _bannerIV.userInteractionEnabled = YES;
    
    
    [self setBannerImageView:NO];
    [self addSubview:_bannerIV];
    
    self.layer.cornerRadius = frame.size.width * 0.5;
    self.layer.masksToBounds = YES;
    self.layer.borderWidth = 1.0;
    self.layer.borderColor = [[UIColor grayColor] CGColor];
    self.backgroundColor = [UIColor colorWithRed:255.0 green:255.0 blue:255.0 alpha:0.83];
    
    self.userInteractionEnabled = YES;
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(floatBtnHide) userInfo:nil repeats:NO];
    
//     添加手势
    [self addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]];
    [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)]];
    
}

- (void)rememberLocation{
    
    [[NSUserDefaults standardUserDefaults] setValue:NSStringFromCGRect(self.frame) forKey:@"float_location"];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)setBannerImageView:(BOOL)bHide {
    NSString *path = nil;
    
//    if (bHide)     {
//        path = @"menu_icon_hide"; //灰色
//    } else {
//        path = @"menu_common_hide"; //彩色
//    }
    
    path = @"img_float_selected"; //悬浮图片
    UIImage *img = [UIImage imageWithName:path];
    [_bannerIV setImage:img];
}

- (void)computeOfLocation:(void(^)())complete
{
    float x = self.center.x;
    float y = self.center.y;
    CGPoint m = CGPointZero;
    m.x = x;
    m.y = y;
    
    //由于这里要展开菜单，所以只取两边就好--------------------------
    if (x < _w/2)
    {
        _locationTag = kLocationTag_left;
    }else
    {
        _locationTag = kLocationTag_right;
    }
    
    //---------------------------------------------------------
    
    if (_hiding) {
        
        switch (_locationTag)
        {
            case kLocationTag_left:
                m.x = 0;
                break;
            case kLocationTag_right:
                m.x = _w;
                break;
            default:
                break;
        }
        
        if (m.x > _w)
            m.x = _w;
        if (m.y > _h - self.frame.size.height/2)
            m.y = _h - self.frame.size.height/2;
        
        
    }else{
        
        switch (_locationTag)
        {
            case kLocationTag_left:
                m.x = 0 + self.frame.size.height/2;
                break;
            case kLocationTag_right:
                m.x = _w - self.frame.size.width/2;
                break;
            default:
                break;
        }
        
        //这个是在旋转是微调浮标出界时
        if (m.x > _w - _bannerIV.frame.size.width/2)
            m.x = _w - _bannerIV.frame.size.width/2;
        if (m.y > _h - _bannerIV.frame.size.height/2)
            m.y = _h - _bannerIV.frame.size.height/2;
        
    }
    
    
    
    [UIView animateWithDuration:0.1 animations:^
     {
         [self setCenter:m];
     } completion:^(BOOL finished)
     {
         complete();
     }];
    
}

#pragma mark - UIGestureRecognizer
- (void)pan:(UIPanGestureRecognizer *)pan{
    
    [self setBannerImageView:NO];
    UIView *view = pan.view;
    CGPoint transPoint = [pan translationInView:view];
    CGPoint center = view.center;
    center.x += transPoint.x;
    center.y += transPoint.y;
    view.center = center;
    [pan setTranslation:CGPointZero inView:view];
    if (pan.state == UIGestureRecognizerStateEnded) {
        _hiding = NO;
        [self computeOfLocation:^
         {
         [_timer invalidate];
         _timer = nil;
         _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(floatBtnHide) userInfo:nil repeats:NO];
         }];

    }
    
}

- (void)tap:(UITapGestureRecognizer *)tap{
    _hiding = NO;
    [self showUserCenter];
    [self setBannerImageView:NO];
    [self computeOfLocation:^
     {
         [_timer invalidate];
         _timer = nil;
         _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(floatBtnHide) userInfo:nil repeats:NO];
     }];
}



#pragma mark - action
- (void)showUserCenter {
    
//    [self setBannerImageView:NO]; // 悬浮按钮变灰
    [[PywSdk manger] showCenter];
    [_timer invalidate];
    _timer = nil;
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(floatBtnHide) userInfo:nil repeats:NO];
}

- (void)floatBtnHide
{
    _hiding = YES;
    _timer = nil;
    [self setBannerImageView:YES];
    [self computeOfLocation:^{
        
    }];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if ([[anim valueForKey:@"toViewKey"] isEqualToString:@"toViewValue"])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.userInteractionEnabled = YES;
        });
    }
}

#pragma mark - 阻止事件传递下去

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}

#pragma mark - NSNotification

- (void)deviceOrientationDidChange:(NSNotification *)notification
{
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (_orientation == orientation) return;
    
    void(^func)(BOOL b) = ^(BOOL b)
    {
        switch (orientation)
        {
            case UIInterfaceOrientationPortrait:
            case UIInterfaceOrientationPortraitUpsideDown:
            {
                _w = self.v_width;
                _h = self.v_height;
                
                break;
            }
            case UIInterfaceOrientationLandscapeLeft:
            case UIInterfaceOrientationLandscapeRight:
            {
                _w = self.h_width;
                _h = self.h_height;
                
                break;
            }
            default:
                break;
        }
        [self computeOfLocation:^{
            
        }];
    };
    
    func(NO);
    
    _orientation = orientation;
}


- (CGFloat)v_height
{
    return [UIScreen mainScreen].bounds.size.height > [UIScreen mainScreen].bounds.size.width ? [UIScreen mainScreen].bounds.size.height : [UIScreen mainScreen].bounds.size.width;
}

- (CGFloat)v_width
{
    return [UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height ? [UIScreen mainScreen].bounds.size.width : [UIScreen mainScreen].bounds.size.height;
}

- (CGFloat)h_width
{
    return ([UIScreen mainScreen].bounds.size.width <[UIScreen mainScreen].bounds.size.height ? [UIScreen mainScreen].bounds.size.height : [UIScreen mainScreen].bounds.size.width);
}

- (CGFloat)h_height
{
    return [UIScreen mainScreen].bounds.size.height >[UIScreen mainScreen].bounds.size.width ? [UIScreen mainScreen].bounds.size.width : [UIScreen mainScreen].bounds.size.height;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
